package tool

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

// GenerateSignature 根据给定的参数和密钥生成MD5签名
func GenerateSignature(amount, bankCardNo, mid, orderId, key string) (string, error) {
	// 按照指定顺序拼接字符串
	signatureString := fmt.Sprintf(
		"amount=%s&bankcardno=%s&mid=%s&orderid=%s&key=%s",
		amount, bankCardNo, mid, orderId, key,
	)
	// 计算MD5哈希
	hasher := md5.New()
	_, err := hasher.Write([]byte(signatureString))
	if err != nil {
		return "", err
	}
	// 获取MD5哈希的十六进制表示并转换为小写
	signature := hex.EncodeToString(hasher.Sum(nil))
	fmt.Println("MD5 Signature:", signature)
	return signature, nil
}

// GenerateSignatureByPay 根据给定的参数和密钥生成MD5签名
func GenerateSignatureByPay(mid, orderid, amount, note, paytype, notifyurl, returnurl, key string) (string, error) {
	// 按照指定顺序拼接字符串
	signatureString := fmt.Sprintf(
		"mid=%s&orderid=%s&amount=%s&note=%s&paytype=%s&notifyurl=%s&returnurl=%s&%s",
		mid, orderid, amount, note, paytype, notifyurl, returnurl, key,
	)

	// 计算MD5哈希
	hasher := md5.New()
	_, err := hasher.Write([]byte(signatureString))
	if err != nil {
		return "", err
	}

	// 获取MD5哈希的十六进制表示并转换为小写
	signature := hex.EncodeToString(hasher.Sum(nil))
	return signature, nil
}

// GenerateSignatureByBPayoutNotify 根据给定的参数和密钥生成MD5签名
func GenerateSignatureByBPayoutNotify(Mid, Id, OrderId, OrderAmount, SecretKey string) (string, error) {
	// 按照指定顺序拼接字符串
	signatureString := fmt.Sprintf(
		"mid=%s&status=%s&id=%s&orderid=%s&orderamount=%s&%s",
		Mid, "1", Id, OrderId, OrderAmount, SecretKey,
	)

	// 计算MD5哈希
	hasher := md5.New()
	_, err := hasher.Write([]byte(signatureString))
	if err != nil {
		return "", err
	}

	// 获取MD5哈希的十六进制表示并转换为小写
	signature := hex.EncodeToString(hasher.Sum(nil))
	return signature, nil
}

// ConvertStringMapToStringInterfaceMap converts a map[string]string to a map[string]interface{}.
func ConvertStringMapToStringInterfaceMap(originalMap map[string]string) map[string]interface{} {
	convertedMap := make(map[string]interface{}, len(originalMap))
	for key, value := range originalMap {
		convertedMap[key] = value // string can be implicitly converted to interface{}
	}
	return convertedMap
}
